package com.tianqu.tms.www.transfer.action;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsAction;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.base.UserContextImpl;
import com.tianqu.tms.core.exception.LoginException;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.www.transfer.controller.TransferLiveDetailController;

public class TransferLiveDetailAction extends TmsAction {
	private static final String REQUEST_PARAM_LANGUAGE  = "language_choice";
	
	private Logger logger = Logger.getLogger(TransferLiveDetailAction.class);

	/**
	 * @return
	 */
	protected boolean isLogedIn() {
		return false;
	}
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		ActionForward forward = null;
	    UserContext uc = (UserContextImpl) request.getSession().getAttribute(TmsConstants.USER_CONTEXT_KEY);
	    if (uc != null) { 
	    	uc.clear(); 
	    	request.getSession().invalidate(); 
	    }
		forward = super.execute(mapping, form, request, response);
		return forward;
	}
	
	/*
	 */
	protected ActionForward doAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, 
			HttpServletResponse response, UserContext uc) throws Exception {
		if (uc != null) {
			uc.clear();
			uc.setUserProfile(null);
		}
		HttpSession session = request.getSession(true);
		
		TransferLiveDetailController loginController = new TransferLiveDetailController();
		try{
			loginController.execute(uc);
		} catch(TmsException e){
			if(e instanceof LoginException ) {
				setErrorsToRequest(request, e.getExceptionId(),e.getErrorParams());
				return mapping.getInputForward();
			} else{
				throw e;
			}
		}
		
		// Locale设定
		selectLocale(request, uc);
		session.setAttribute(TmsConstants.USER_CONTEXT_KEY, uc);
		return mapping.findForward(TmsConstants.SUCCESS);
	}
	/**
	 * 设置语言
	 * @param request
	 * @param uc
	 */
	private void selectLocale(HttpServletRequest request, UserContext uc) {
		
		Locale loc = getLocale(request);
		String lang = request.getParameter(REQUEST_PARAM_LANGUAGE);
		if (lang == null) { lang = uc.getUserProfile().getLocallangCode(); }
		
		if ("en".equals(lang)) {
			loc = Locale.ENGLISH;    logger.debug("locale set to " + loc);
		} else { // cn is default
			loc = Locale.CHINESE;    logger.debug("locale set to " + loc);
		}

		setLocale(request, loc);
		uc.setLanguage(loc.getLanguage());
	}
}